package com.channel.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.channel.modules.system.domain.Dept;
import com.channel.modules.system.service.DeptService;
import com.channel.modules.system.service.dto.DeptDto;
import com.channel.modules.system.service.dto.DeptQueryCriteria;
import com.commons.base.BaseEntity;
import com.commons.exception.BadRequestException;
import com.commons.utils.PageResult;
import com.commons.utils.PageUtil;
import dj.framework.annotation.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/dept")
public class DeptController {

    private final DeptService deptService;
    private static final String ENTITY_NAME = "dept";

    @Autowired
    public DeptController(DeptService deptService) {
        this.deptService = deptService;
    }

    //导出部门数据
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('dept:list')")
    public void exportDept(HttpServletResponse response, DeptQueryCriteria criteria) throws Exception{
        deptService.download(deptService.queryAll(criteria,false),response);
    }

    //查询部门
    @GetMapping
    @PreAuthorize("@el.check('user:list','dept:list')")
    public ResponseEntity<PageResult<DeptDto>> queryDept(DeptQueryCriteria criteria) throws Exception{
        List<DeptDto> depts=deptService.queryAll(criteria,true);
        return new ResponseEntity<>(PageUtil.toPage(depts,depts.size()), HttpStatus.OK);
    }

    //查询部门：根据ID获取同级与上级部门
    @PostMapping("/superior")
    @PreAuthorize("@el.check('user:list','dept:list')")
    public ResponseEntity<Object> getDeptSuperior(@RequestBody List<Long> ids,@RequestParam(defaultValue = "false") Boolean exclude) {
        Set<DeptDto> deptSet=new LinkedHashSet<>();
        for(Long id:ids){
            DeptDto deptDto=deptService.findById(id);
            List<DeptDto> depts=deptService.getSuperior(deptDto,new ArrayList<>());
            if(exclude){
                for(DeptDto dept:depts){
                    if(dept.getId().equals(dept.getPid())){
                        dept.setSubCount(dept.getSubCount()-1);
                    }
                }
                //编辑部门时不显示自己以及下级的数据
                depts=depts.stream().filter(i->!ids.contains(i.getId())).collect(Collectors.toList());
                deptSet.addAll(depts);
            }
        }
        return new ResponseEntity<>(deptService.buildTree(new ArrayList<>(deptSet)),HttpStatus.OK);
    }

    @Log("新增部门")
    @PostMapping
    @PreAuthorize("@el.check('dept:add')")
    public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources){
        if(resources.getId()!=null){
            throw new BadRequestException("A new "+ENTITY_NAME+"cannot already have an ID");
        }
        deptService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改部门")
    @PutMapping
    @PreAuthorize("@el.check('dept:edit')")
    public ResponseEntity<Object> updateDept(@Validated(BaseEntity.Update.class) @RequestBody Dept resources){
        deptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除部门")
    @DeleteMapping
    @PreAuthorize("@el.check('dept:del')")
    public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){
        Set<DeptDto> deptDtos=new HashSet<>();
        for(Long id:ids){
            List<Dept> deptList = deptService.findByPid(id);
            deptDtos.add(deptService.findById(id));
            if(CollectionUtil.isNotEmpty(deptList)){
                deptDtos=deptService.getDeleteDepts(deptList,deptDtos);
            }
        }
        //验证是否按角色或用户关联
        deptService.verification(deptDtos);
        deptService.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
